package 预科0104ChattingRoom_Q5;


import java.io.*;
import java.net.Socket;

public class ChatThread extends Thread {

    private int socketNum;
    private String name;

    public ChatThread (int socketNum,String name){
        this.socketNum = socketNum;
        this.name = name;
    }

    @Override
    public void run(){

        BufferedReader bufferedReader = null;

        try {

            bufferedReader = new BufferedReader(new InputStreamReader(ServerTest.sockets.get(socketNum).getInputStream()));

            while (true) {

                String msg = bufferedReader.readLine();
                if(null == msg){
                    System.out.println(name + "已下线");
                    break;
                }

                else if("file".equalsIgnoreCase(msg)){
 //读取文件名
                    String filename = bufferedReader.readLine();
                    System.out.println(name + " 发送" + filename);

                    Function.FileReceiver(socketNum, filename);
                    Function.Stringsend("上传的" +filename,name);
                    for(Socket i: ServerTest.sockets ) {
                    	if(i.equals(ServerTest.sockets.get(socketNum))) {
                    		continue;
                    	}
                    	if(new File(ServerTest.severfile + "/" + filename).exists()){
                            new PrintStream(i.getOutputStream()).println("file");
                            new PrintStream(i.getOutputStream()).println(filename);
                            Function.Fileshare(ServerTest.sockets.indexOf(i),filename);

                        }
                        else {
                            new PrintStream(i.getOutputStream()).println("file");
                            new PrintStream(i.getOutputStream()).println("fail");
                        }
                    }
                    
                }
                else {
                    System.out.println(name + "：" + msg);
                    Function.Stringsend(msg,name);

                    }
                }

        }
        catch(IOException e){
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }



    }


}
